<template>
  <div class="mapdialog d-center" v-show="dialogFormVisible" @click.self="blackClick">
    <div class="viewDiv" id="viewDiv"></div>
    <lotDialog
      :dialogFormVisible1="dialogFormVisible1"
      @close="close1"
      :item="item"
      :inner="inner"
      :Xscode="Xscode"
      :xmmc="xmmc"
    />
  </div>
</template>

<script>
import { loadCss, loadModules } from "esri-loader";
import lotDialog from "./dialog/lotDialog.vue";
export default {
  name: "mapdialog",
  components: {
    lotDialog,
  },
  data() {
    return {
      dialogFormVisible: false,
      dialogFormVisible1: false,
      gisConstructor: {}, //gis 构造函数
      gisInstance: {}, // gis 实例
      layersInstance: {},
      UIInstance: {},
      gisModules: [
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/MapImageLayer",
        "esri/layers/TileLayer",
        "esri/layers/FeatureLayer",
        "esri/widgets/LayerList",
        "esri/widgets/AreaMeasurement2D",
        "esri/widgets/DistanceMeasurement2D",
        "esri/widgets/Zoom",
        "esri/widgets/Zoom/ZoomViewModel",
        "esri/geometry/Point",
        "esri/Graphic",
        "esri/tasks/QueryTask",
        "esri/tasks/support/Query",
        "esri/geometry/SpatialReference",
        "esri/geometry/Extent",
        "esri/symbols/TextSymbol",
        "esri/symbols/PictureMarkerSymbol",
        "esri/Color",
        "esri/symbols/Font",
        "esri/tasks/IdentifyTask",
        "esri/tasks/support/IdentifyParameters",
        "esri/layers/GraphicsLayer",
        "esri/widgets/Sketch/SketchViewModel",
        "esri/views/2d/draw/Draw",
        "esri/geometry/Polygon",
        "esri/core/watchUtils",
        "esri/core/urlUtils",
        "esri/identity/IdentityManager",
        "esri/identity/ServerInfo",
        "esri/widgets/Legend",
        "esri/geometry/support/webMercatorUtils",
      ],
      options: {
        url: "https://js.arcgis.com/4.15/",
        // url: this.$jsApi + "arcgis_js_api/library/4.14/init.js"
      },
      layerUrl: this.$map + "arcgis/rest/services/Gis2013_PROJ_LD/MapServer/",
      bgUrl: this.$map + "arcgis/rest/services/BeiJingProj/MapServer/",
      xmmc: "",
      items: null,
      resultData: null,
      img3: require("../../assets/img/infobox-close.png"),
      img4: require("../../assets/img/ic_location_blue.png"),
      img5: require("../../assets/img/ic_info.png"),
      imgs: require("../../assets/img/dot_end.png"),
      imgs2: require("../../assets/img/dot_start.png"),
      xm_id: null,
      item: {},
      inner: [],
      Xscode: [],
      token: "",
    };
  },
  mounted() {
    this.$Bus.$on("local", (resultData, xmmc) => {
      // console.log(resultData)
      // console.log(xmmc)
      this.xmmc = xmmc;
      this.xm;
      this.dialogFormVisible = true;
      this.gisInstance.view.graphics.removeAll();
      this.resultData = resultData;
      this.local(resultData);
    });
    this.$get("/api/index/codes", { pid: 17 }).then((res) => {
      if (res.code == 200 && res.data) {
        this.inner = res.data.list;
      }
    });
    this.$get("/api/index/codes", { pid: 25 }).then((res) => {
      if (res.code == 200 && res.data) {
        this.Xscode = res.data.list;
      }
    });
    this.init();
    let that = this;
    window.closePopMap = function () {
      that.gisInstance.view.graphics.items = that.gisInstance.view.graphics.items.filter(
        (v) => {
          return !("attr" in v);
        }
      );
      var dom = document.querySelectorAll(".pulse");
      if (dom.length > 0) {
        dom.forEach((v) => {
          v.remove();
        });
      }
      var div = document.querySelectorAll(".poptemplate");
      if (div.length > 0) {
        div.forEach((v) => {
          v.remove();
        });
      }
    };
    window.showFormMap = function () {
      that.dialogFormVisible1 = true;
    };
  },
  methods: {
    close1() {
      this.dialogFormVisible1 = false;
    },
    blackClick() {
      this.gisInstance.view.graphics.removeAll();
      this.dialogFormVisible = false;
    },
    local(resultData) {

      let centerOut;
      if (!resultData.length) return;
      resultData.forEach((v) => {
        let line = v.lines;


        // var pc = line.paths[0];
        var start = line[0]; //起点坐标
        var end = line[line.length - 1]; //止点坐标
        var center; //中心点坐标
        var arrowStartIndex, arrowEndIndex;

        if (line.length % 2 == 0) {
          arrowEndIndex = Math.round(line.length / 2);
          arrowStartIndex = Math.round(line.length / 2 - 1);
          var extent = new this.gisConstructor.Extent(
            line[arrowStartIndex][0],
            line[arrowStartIndex][1],
            line[arrowEndIndex][0],
            line[arrowEndIndex][1],
            new this.gisConstructor.SpatialReference({ wkid: 3857 })
          );
          center = [extent.center.x, extent.center.y];
        } else {
          arrowEndIndex = Math.round(line.length / 2 + 1);
          arrowStartIndex = Math.round(line.length / 2 - 1);
          center = line[Math.round(line.length / 2)];
        }

        var startPoint = {
          geometry: {
            type: "point",
            x: start[0],
            y: start[1],
            spatialReference: { wkid: 3857 },
          },
          symbol: {
            type: "picture-marker", // autocasts as new PictureMarkerSymbol()
            url: this.imgs2,
            width: "10px",
            height: "10px",
          }
          // symbol: {
          //   color: [255, 0, 0],
          //   size: 10,
          //   type: "simple-marker",
          // },
        };

        var endPoint = {
          geometry: {
            type: "point",
            x: end[0],
            y: end[1],
            spatialReference: { wkid: 3857 },
          },
          symbol: {
            type: "picture-marker", // autocasts as new PictureMarkerSymbol()
            url: this.imgs,
            width: "10px",
            height: "10px",
          }
          // symbol: {
          //   color: [0, 128, 0],
          //   size: 10,
          //   type: "simple-marker",
          // },
        };
        var lineGraphic = {
          geometry: {
            type: "polyline",
            paths: [line],
            spatialReference: { wkid: 3857 },
          },
          symbol: {
            type: "simple-line",
            color: "#4A8DFC",
            width: 4,
          },
          attributes: {
            bd_id: v.bd_Id,
            x: center[0],
            y: center[1],
          },
        };

        // console.log(gStart);
        // console.log(graphic.geometry);
        lineGraphic.geometry = this.gisConstructor.webMercatorUtils.geographicToWebMercator(
          lineGraphic.geometry
        );

        startPoint.geometry = this.gisConstructor.webMercatorUtils.geographicToWebMercator(
          startPoint.geometry
        );

        endPoint.geometry = this.gisConstructor.webMercatorUtils.geographicToWebMercator(
          endPoint.geometry
        );
        var gStart = new this.gisConstructor.Graphic(startPoint);
        var gEnd = new this.gisConstructor.Graphic(endPoint);
        var graphic = new this.gisConstructor.Graphic(lineGraphic);

        this.gisInstance.view.graphics.add(graphic);
        this.gisInstance.view.graphics.add(gStart);
        this.gisInstance.view.graphics.add(gEnd);
        centerOut = center;
      });
      let pointAll = {
        longitude: centerOut[0],
        latitude: centerOut[1],
        spatialReference: {
          wkid: 3857,
        },
      };
      pointAll = this.gisConstructor.webMercatorUtils.geographicToWebMercator(
        pointAll
      );
      this.gisInstance.point = new this.gisConstructor.Point(pointAll);
      // console.log(centerOut)
      this.gisInstance.view.goTo({
        target: this.gisInstance.point,
        zoom: 5,
        speedFactor: 6,
        easing: "linear",
      });
    },
    init() {
      let url = "http://121.89.201.182:6080/";
      loadCss("https://js.arcgis.com/4.15/esri/themes/light/main.css");
      loadModules(this.gisModules, this.options).then((res) => {
        for (var i in res) {
          var name = this.gisModules[i].split("/").pop();
          this.gisConstructor[name] = res[i];
        }
        //获取Token
        var serverInfo = this.gisConstructor.ServerInfo();
        var identityManager = this.gisConstructor.IdentityManager;

        serverInfo.serverString = url + "arcgis/rest/services"; //这里配置ArcGIS Server的REST服务地址
        serverInfo.tokenServiceUrl = url + "arcgis/tokens/generateToken"; //由于GIS Server和Portal联合了，所以使用Portal的token生成地址
        var userInfo = { username: "zzUser", password: "gis_1234" }; //这里填写Portal的用户和密码
        identityManager.generateToken(serverInfo, userInfo).then(
          (data) => {
            // This is called when the promise resolves
            var tokenValue = data.token;
            this.token = data.token;
            //注册Token，注册之后，在Portal里的所有资源，只要该用户由权限访问，就可以直接使用，之前的所有安全服务请求都将会把token值作为参数发送到服务器端
            identityManager.registerToken({
              server: url + "arcgis/rest/services",
              token: tokenValue,
            });
            loadModules(this.gisModules, this.options).then(this.loadMap);
          },
          function (error) {
            // This function is called when the promise is rejected
            console.log(error); // Logs the error message
          }
        );
      });
    },
    //初始化地图
    loadMap(res) {
      for (var i in res) {
        var name = this.gisModules[i].split("/").pop();
        this.gisConstructor[name] = res[i];
      }
      // this.gisConstructor.urlUtils.addProxyRule({
      //   urlPrefix: this.$map, //配置文件proxy.config中的地址,要请求的地址
      //   proxyUrl: this.$proxy + "/DotNet/proxy.ashx", //部署的代理文件地址
      // });
      this.layersInstance.bgLayer = new this.gisConstructor.TileLayer({
        url: this.bgUrl,
      });
      this.layersInstance.layer = new this.gisConstructor.MapImageLayer({
        url: this.layerUrl,
      });

      this.gisInstance.map = new this.gisConstructor.Map({
        spatialReference: {
          wkid: 3857,
        },
      });

      this.gisInstance.view = new this.gisConstructor.MapView({
        container: "viewDiv",
        spatialReference: {
          wkid: 3857,
        },
        constraints: {
          rotationEnabled: false, //禁止旋转
        },
        zoom: 2,
        map: this.gisInstance.map,
      });

      this.gisInstance.map.add(this.layersInstance.bgLayer);
      this.gisInstance.map.add(this.layersInstance.layer);

      //======================================
      this.UIInstance.zoom = new this.gisConstructor.Zoom({
        viewModel: {
          view: this.gisInstance.view,
        },
      });

      this.UIshow();
      // this.popupMap();
      this.gisInstance.view.when(this.pointerUpLocation);
    },
    UIshow() {
      this.gisInstance.view.ui.remove("attribution"); //移除底部ESRI logo
      this.gisInstance.view.ui._removeComponents(["zoom"]); //移除默认ui
    },
    pointerUpLocation() {
      this.gisInstance.view.on("click", (event) => {
        this.gisInstance.view.hitTest(event).then(this.popup);
      });
      // this.gisConstructor.watchUtils.when(
      //   this.gisInstance.view,
      //   "extent",
      //   // this.animation
      // );
      this.gisConstructor.watchUtils.when(
        this.gisInstance.view,
        "extent",
        this.poptemplate
      );
      this.items = this.gisInstance.view.graphics.items;
    },
    popup(response) {
      let that = this;
      if (response.results.length) {
        let results = response.results;
        let result = results.filter((v) => {
          return v.graphic.geometry.type == "polyline";
        });
        if (!result.length) return;
        let center = result[0].graphic.attributes;
        this.gisInstance.view.graphics.items = this.gisInstance.view.graphics.items.filter(
          (v) => {
            return !("attr" in v);
          }
        );
        var dom = document.querySelectorAll(".pulse");
        if (dom.length > 0) {
          dom.forEach((v) => {
            v.remove();
          });
        }
        var div = document.querySelectorAll(".poptemplate");
        if (div.length > 0) {
          div.forEach((v) => {
            v.remove();
          });
        }
        let bd_id = result[0].graphic.attributes.bd_id;
        that
          .$get("/api/QqBdgl/one", {
            bd_id: bd_id,
          })
          .then((res) => {
            let data = res.data;
            this.item = res.data;
            let result = {
              xmmc: this.xmmc,
              bdmc: res.data.bdmc,
              zbj: res.data.zbj,
              bd_id: bd_id,
            };
            let reqs = [];
            reqs.push(
              this.$get("/api/enterprise/getInfo", { id: data.zbdw_id }).then(
                (res1) => {
                  result.zbdw = res1.data.dwmc;
                }
              )
            );
            reqs.push(
              this.$get("/api/project/getUserIds", { id: data.xmjl_id }).then(
                (res2) => {
                  result.xmjl_xm = res2.data[0].xm;
                  result.xmjl_lxdh = res2.data[0].lxdh;
                }
              )
            );
            reqs.push(
              this.$get("/api/QqHtgl/getHtListByDbId", {
                bd_id: bd_id,
              }).then((res3) => {
                result.htje = res3.data[0].ht_je;
              })
            );
            Promise.all(reqs)
              .then(() => {
                var popPoint = {
                  geometry: {
                    type: "point",
                    x: center.x,
                    y: center.y,
                  },
                  symbol: {
                    color: "rgba(255,255,255,0)",
                    size: 0,
                    type: "simple-marker",
                  },
                };
                popPoint.geometry = this.gisConstructor.webMercatorUtils.geographicToWebMercator(
                  popPoint.geometry
                );
                var popGraphic = new this.gisConstructor.Graphic(popPoint);
                popGraphic.pop = {
                  x: center.x,
                  y: center.y,
                };
                popGraphic.attr = {
                  x: center.x,
                  y: center.y,
                };
                this.gisInstance.view.graphics.add(popGraphic);
                let title = this.createTitle("BD", result);
                this.poptemplate(title);
                // this.animation();
              })
              .catch(() => {
                var popPoint = {
                  geometry: {
                    type: "point",
                    x: center.x,
                    y: center.y,
                  },
                  symbol: {
                    color: "rgba(255,255,255,0)",
                    size: 0,
                    type: "simple-marker",
                  },
                };
                popPoint.geometry = this.gisConstructor.webMercatorUtils.geographicToWebMercator(
                  popPoint.geometry
                );
                var popGraphic = new this.gisConstructor.Graphic(popPoint);
                popGraphic.pop = {
                  x: center.x,
                  y: center.y,
                };
                popGraphic.attr = {
                  x: center.x,
                  y: center.y,
                };
                this.gisInstance.view.graphics.add(popGraphic);
                let title = this.createTitle("BD", result);
                this.poptemplate(title);
                // this.animation();
              });
          });
      }
    },
    createTitle(type, graphic) {
      var title = "";
      if (type == "BD") {
        title = `<div style='height:100%; width:100%;' class='popup_select' >
                          <div class="header">
                           <div class="hang">${graphic["xmmc"]}</div>
                               <i  onclick="closePopMap()" >
                                ×
                                </i>
                           </div>
                           <div class="center">
                               <div class="hang">
                               <span>标段名称 : </span>
                               <span>${graphic["bdmc"] || "暂无数据"} </span>
                               </div>
                               <div class="hang">
                               <span>中标价 : </span>
                               <span>${graphic["zbj"] || "暂无数据"} 万元</span>
                               </div>
                               <div class="hang">
                               <span>合同金额 : </span>
                               <span>${
                                 graphic["htje"] || "暂无数据"
                               } 万元</span>
                               </div>
                               <div class="hang">
                               <span>中标单位 :</span>
                               <span>${graphic["zbdw"] || "暂无数据"} </span>
                               </div>
                               <div class="hang">
                               <span>项目经理及联系方式 : </span>
                               <span>${graphic["xmjl_xm"] || "暂无数据"}-${
          graphic["xmjl_lxdh"] || "暂无数据"
        } </span>
                               </div>
                           </div>
                           <div class="fotter">
                                 <span onclick="showFormMap('${
                                   graphic["bd_id"]
                                 }')">
                              
                                查看详情
                              </span>
                          </div>
                          </div>`;
      }
      return title;
    },
    //点击添加点动画
    animation() {
      if (this.gisInstance.view.graphics.items.length > 0) {
        this.gisInstance.view.graphics.items.forEach((v) => {
          if ("attr" in v) {
            var xx = v.attr.x;
            var yy = v.attr.y;
            var dom = document.getElementById("point" + v.uid + "");
            let pointAll = {
              x: xx,
              y: yy,
              spatialReference: {
                wkid: 3857,
              },
            };
            pointAll = this.gisConstructor.webMercatorUtils.geographicToWebMercator(
              pointAll
            );
            var point1 = this.gisInstance.view.toScreen(
              new this.gisConstructor.Point(pointAll)
            );
            var { x, y } = point1;
            if (!dom) {
              dom = document.createElement("div");
              dom.className = "pulse";
              dom.id = "point" + v.uid;
              document.getElementById("viewDiv").appendChild(dom);
            }
            dom.style = `left:${x - 10}px;top:${y - 10}px`;
          }
        });
      }
    },
    poptemplate(value) {
      if (this.gisInstance.view.graphics.items.length > 0) {
        this.gisInstance.view.graphics.items.forEach((v) => {
          if ("pop" in v) {
            var xx = v.pop.x;
            var yy = v.pop.y;
            var div = document.getElementById("pop" + v.uid + "");
            let pointAll = {
              x: xx,
              y: yy,
              spatialReference: {
                wkid: 3857,
              },
            };
            pointAll = this.gisConstructor.webMercatorUtils.geographicToWebMercator(
              pointAll
            );
            var point1 = this.gisInstance.view.toScreen(
              new this.gisConstructor.Point(pointAll)
            );
            var { x, y } = point1;
            if (!div && typeof value == "string") {
              div = document.createElement("div");
              var div1 = document.createElement("div");
              var div2 = document.createElement("div");
              div2.className = "angle";
              div.id = "pop" + v.uid;
              div.className = "poptemplate";
              document.getElementById("viewDiv").appendChild(div);
              div.appendChild(div1);
              div.appendChild(div2);
              div1.innerHTML = value;
            }
            if (div) {
              var height = div.offsetHeight;
              div.style = `left:${x - 140}px;top:${y - 32 - height}px`;
            }
          }
        });
      }
    },
  },
  watch: {
    items(news) {
      if (news.length == 0) {
        var dom = document.querySelectorAll(".pulse");
        if (dom.length > 0) {
          dom.forEach((v) => {
            v.remove();
          });
        }
        var div = document.querySelectorAll(".poptemplate");
        if (div.length > 0) {
          div.forEach((v) => {
            v.remove();
          });
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.mapdialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2400;
  background: #555555c2;
}
.viewDiv {
  width: 80%;
  height: 80%;
  // z-index: 10000;
  background: white;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}
</style>